package com.tao.lab.utils

import android.Manifest
import android.app.Activity
import android.bluetooth.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import androidx.annotation.RequiresApi
import java.lang.reflect.Method
import java.util.*


/**
 * @description: lab
 * @author: wangxf
 * @date: 2023/5/15 11:06
 */
val REQUEST_ENABLE_BT: Int = 1001;

class BlueToothUtils {

    @RequiresApi(Build.VERSION_CODES.M)
    fun open(context: Activity) {
        context.requestPermissions(
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_BACKGROUND_LOCATION,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.BLUETOOTH_SCAN,
            ), 100
        )

        val bluetoothManager =
            context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        var blueAdapter = bluetoothManager.adapter;
        if (blueAdapter.isEnabled) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
//            context.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
        }
        //获取已配对设备列表
//        blueAdapter.bondedDevices;
        // 扫描设备
//        blueAdapter.startDiscovery();
        // Register the BroadcastReceiver
        var filter = IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction("android.bluetooth.input.profile.action.CONNECTION_STATE_CHANGED");
        context.registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                intent?.let {
                    if (BluetoothDevice.ACTION_FOUND.equals(it.action)) {
                        // Get the BluetoothDevice object from the Intent
                        var device: BluetoothDevice? =
                            it.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)

                    }
                }
            }

        }, filter);


        //bluetooth 作为服务端
//        var service = blueAdapter.listenUsingRfcommWithServiceRecord("Tao", UUID.fromString(""))

//        val accept = service.accept();

//        var serviceL2 = blueAdapter.listenUsingL2capChannel();

//        var acceptL2 = serviceL2.accept();


        //bluetooth 作为客户端

        var device: BluetoothDevice? = null;
//        var blueToothIo = device!!.createRfcommSocketToServiceRecord(UUID.fromString(""))
//        var blueToothL2 = device!!.createL2capChannel(1)


//        blueToothIo.inputStream;
//        blueToothIo.outputStream;
//
//        blueToothL2.inputStream;
//        blueToothL2.outputStream;

        var mBluetoothHeadset: BluetoothHeadset?

        var proxy = blueAdapter.getProfileProxy(context, object : BluetoothProfile.ServiceListener {
            override fun onServiceConnected(profile: Int, proxy: BluetoothProfile?) {
                if (profile === BluetoothProfile.HEADSET) {
                    mBluetoothHeadset = proxy as BluetoothHeadset//蓝牙耳机
                }
                if (profile === BluetoothProfile.A2DP) {
                    var mBluetoothHeadset = proxy as BluetoothA2dp//蓝牙音响
                    var bluetoothHealth = proxy as BluetoothHealth//蓝牙音响
//                    bluetoothHealth.connectChannelToSource(device)
//                    bluetoothHealth.registerSinkAppConfiguration()
                }
            }

            override fun onServiceDisconnected(profile: Int) {
                if (profile === BluetoothProfile.HEADSET) {
                    mBluetoothHeadset = null;
                }
            }
        }, BluetoothProfile.HEADSET)


    }

//    private fun pairDevice(mTargetDevice: BluetoothDevice) {
//        if (mTargetDevice.getBondState() !== BluetoothDevice.BOND_NONE) {
//            return
//        }
//        mTargetDevice.createBond()
//    }

    private fun connectDevice(mBluetoothHeadset: BluetoothHeadset, mTargetDevice: Any) {
        if (mBluetoothHeadset == null) {

        } else {
            try {
                //通过反射获取BluetoothA2dp中connect方法
                val connectMethod: Method = BluetoothA2dp::class.java.getMethod(
                    "connect",
                    BluetoothDevice::class.java
                )
                connectMethod.invoke(mBluetoothHeadset, mTargetDevice)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }


    }


}